import requests
import json

BASE_API = "http://widechaos.cn/api/quant"
STRATEGY_TOKEN = "your_secret_key_here"


def send_order(security, amount):
    data_dict = {
        'opType': None,
        'orderType': None,
        'orderCode': security[:6],
        'prType': None,
        'price': None,
        'volume': amount,
        'heart': "qmt_order"
    }
    json_data = {
        "method": "sendMsg",
        "data": json.dumps(data_dict),
        "key": STRATEGY_TOKEN
    }

    try:
        response = requests.post(
            f'{BASE_API}/signal',
            json=json_data,
            timeout=5,
            headers={"Authorization": f"Bearer {STRATEGY_TOKEN}"}
        )
        return response
    except Exception as e:
        print(f"发送信号失败: {e}")
        return None


# 其余包装器函数保持不变...
def qmt_order(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result is None:
            return
        send_order(*args)
        return result

    return wrapper


def qmt_order_target(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result is None:
            return
        send_order(result.security, flag_amount(result.amount, result.is_buy))
        return result

    return wrapper


def qmt_order_value(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result is None:
            return
        send_order(result.security, flag_amount(result.amount, result.is_buy))
        return result

    return wrapper


def qmt_order_target_value(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result is None:
            return
        send_order(result.security, flag_amount(result.amount, result.is_buy))
        return result

    return wrapper


def flag_amount(amount, is_buy):
    return abs(amount) if is_buy else -abs(amount)

def set_server(url: str):
    global BASE_API
    BASE_API = url.rstrip('/')

def set_token(token: str):
    global STRATEGY_TOKEN
    STRATEGY_TOKEN = token
